// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------
const SMSClient = require('@alicloud/sms-sdk');
// ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换
const accessKeyId = 'LTAIP8HnmPaFrJpl';
const secretAccessKey = 'NrHIww6TNfvaX9dz22BRESXFTTO8Pl';
// const queueName = 'Alicom-Queue-1092397003988387-';
const smsClient = new SMSClient({accessKeyId, secretAccessKey});
module.exports = class extends think.cmswing.center {
  /**
     * 注册页面
     */
  async registerAction() {
    if (this.isPost) {
      const data = this.post();
      // 验证
      let res;
      if (think.isEmpty(data.username)) {
        return this.fail('手机号不能为空！');
      } else {
        data.username = data.username.trim();
        const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (reg.test(data.username) === false) {
          return this.fail('手机号格式不正确！');
        }
        res = await this.model('member').where({username: data.username}).find();
        if (!think.isEmpty(res)) {
          return this.fail('手机号已存在，请重新填写！');
        }
      }
      if (think.isEmpty(data.password)) {
        return this.fail('密码不能为空！');
      } else if (data.password.length < 6 || data.password.length > 16) {
        return this.fail('密码限制为6-16位，请重新填写！');
      }
      if (data.repassword != data.password) {
        return this.fail('确认密码与密码不一致！');
      }
      if (data.clause != 'on') {
        return this.fail('必须要同意,网站服务条款');
      }
      if (think.isEmpty(data.sysnumber)) {
        return this.fail('验证码不能为空！');
      } else {
        const date = JSON.stringify(new Date()).substring(1, 5) + JSON.stringify(new Date()).substring(6, 8) + JSON.stringify(new Date()).substring(9, 11);
        const {Code, SmsSendDetailDTOs} = await smsClient.queryDetail({
          PhoneNumber: data.username,
          SendDate: date,
          PageSize: '10',
          CurrentPage: '1'
        });
        if (Code === 'OK') {
          if (SmsSendDetailDTOs.SmsSendDetailDTO.length > 0) {
            const content = SmsSendDetailDTOs.SmsSendDetailDTO[0].Content.substring(8, 14);
            if (data.sysnumber !== content) { return this.fail('验证码不正确！') }
          } else {
            return this.fail('验证码不正确！');
          }
        } else {
          return this.fail('查询验证码出错，请重试！');
        }
      }
      data.status = 1;// 数据状态
      data.reg_time = new Date().valueOf();
      data.reg_ip = _ip2int(this.ip);
      data.password = encryptPassword(data.password);
      data.mobile = data.username;
      data.user_active = 0;
      data.oastatus = 0;
      data.zhucestatus = 0;
      data.groupid = 11;

      const reg = await this.model('member').add(data);
      // 自动登录，返回成功信息
      await this.model('cmswing/member').autoLogin({id: reg}, this.ip);// 更新用户登录信息，自动登陆
      const userInfo = {
        ...data,
        'uid': reg
      };

      await this.session('webuser', userInfo);
      return this.success({name: '注册成功', url: '/'}, data);
    } else {
      this.meta_title = '用户注册';
      return this.isMobile ? this.display(this.mtpl()) : this.display();
    }
  }

  /**
     * 注册页面
     */
  async changepasswordAction() {
    if (this.isPost) {
      const data = this.post();
      // 验证
      let res;
      if (think.isEmpty(data.username)) {
        return this.fail('手机号不能为空！');
      } else {
        data.username = data.username.trim();
        const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if (reg.test(data.username) === false) {
          return this.fail('手机号格式不正确！');
        }
        res = await this.model('member').where({username: data.username}).find();
        if (think.isEmpty(res)) {
          return this.fail('手机号不存在，请重新填写！');
        }
      }
      if (think.isEmpty(data.password)) {
        return this.fail('密码不能为空！');
      } else if (data.password.length < 6 || data.password.length > 16) {
        return this.fail('密码限制为6-16位，请重新填写！');
      }
      if (data.repassword != data.password) {
        return this.fail('确认密码与新密码不一致！');
      }
      if (think.isEmpty(data.sysnumber)) {
        return this.fail('验证码不能为空！');
      } else {
        const date = JSON.stringify(new Date()).substring(1, 5) + JSON.stringify(new Date()).substring(6, 8) + JSON.stringify(new Date()).substring(9, 11);
        const {Code, SmsSendDetailDTOs} = await smsClient.queryDetail({
          PhoneNumber: data.username,
          SendDate: date,
          PageSize: '10',
          CurrentPage: '1'
        });
        if (Code === 'OK') {
          if (SmsSendDetailDTOs.SmsSendDetailDTO.length > 0) {
            const content = SmsSendDetailDTOs.SmsSendDetailDTO[0].Content.substring(8, 14);
            if (data.sysnumber !== content) { return this.fail('验证码不正确！') }
          } else {
            return this.fail('验证码不正确！');
          }
        } else {
          return this.fail('查询验证码出错，请重试！');
        }
      }
      data.password = encryptPassword(data.password);
      const list = await this.model('member').where({username: data.username}).update({password: data.password});
      if (list == 1) {
        return this.success({name: '修改密码成功！', url: '/'}, list);
      } else {
        return this.fail('修改密码失败', list);
      }
    } else {
      this.meta_title = '忘记密码';
      return this.isMobile ? this.display(this.mtpl()) : this.display();
    }
  }

  //   登陆页面
  async loginAction() {
    // 判断公众账号类型
    if (this.config('setup.wx_type') == 4 || this.config('setup.wx_type') == 2) {
      await this.action('center/weixin', 'oauth');
    }
    if (this.isAjax('post')) {
      if (this.config('setup.GEETEST_IS_LOGIN') == 1) {
        // 验证码 钩子
        const signinBefore = await this.hook('loginBefore');
        if (signinBefore === 'no') {
          return this.fail(-3, '验证码不正确!');
        }
      }
      // 用户账号密码验证
      const username = this.post('username');
      let password = this.post('password');
      password = encryptPassword(password);
      let res = await this.model('cmswing/member').signin(username, password, this.ip, 5, 0);
      // 钩子
      if (res && res instanceof Object && res.uid > 0) {
        // 记录用户登录行为
        // await this.model("action").log("user_login", "member", res.uid, res.uid, this.ip(), this.http.url);
        // console.log(111111111111121);
        // console.log(res);
        if (res.is_admin != 0) {
          return this.fail('非会员不能登录电商！');
        };
        await this.session('webuser', res);
        return this.success({name: '登录成功！', user: res});
      } else { // 登录失败
        let fail;
        if (res instanceof Array && res.length > 1) {
          await this.session('users', res);
          res = -4;
        }
        switch (res) {
          case -1:
            fail = '用户不存在或被禁用';
            break; // 系统级别禁用
          case -2:
            fail = '密码错误';
            break;
          case -4:
            fail = '该账号对应多个用户';
            break;
          default:
            fail = '未知错误';
            break; // 0-接口参数错误（调试阶段使用）
        }
        return this.fail(res, fail);
      }
    } else {
      // 如果已经登陆直接跳转到用户中心
      if (this.is_login) {
        return this.redirect('/center/index');
      }
      this.meta_title = '用户登录';
      // 第三方登录钩子
      await this.hook('logins');
      // 登录验证视图钩子
      await this.hook('loginView');
      // 判断浏览客户端
      if (this.isMobile) {
        this.active = 'center/index';
        return this.display(this.mtpl());
      } else {
        if (this.user.roleid == 9) { /* 客户 */
          return this.redirect('/centershop{% if controller.user.mar_class %}?class={{controller.user.mar_class}}{% endif %}');
        } else if (this.user.roleid == 10) {
          return this.redirect('/center/index');
        } else {
          return this.display();
        }
      }
    }
  }

  async loginselectAction() {
    if (this.isPost) {
      const userid = this.post('userid');
      if (think.isEmpty(userid)) {
        return this.fail('请选择一个用户');
      }
      const users = await this.session('users');
      if (think.isEmpty(users)) {
        return this.fail('数据有误，请刷新界面重试。');
      }
      let user = null;
      users.forEach((item) => {
        if (userid == item.id) {
          user = item;
        }
      });
      if (think.isEmpty(user)) {
        return this.fail('数据有误，请刷新界面重试。');
      }
      const username = user.mobile;
      const password = user.password;
      console.log('username:' + username + ',password:' + password);
      let res = await this.model('cmswing/member').signin(username, password, this.ip, 5, 0);
      // 钩子
      if (res && res instanceof Object && res.uid > 0) {
        // 记录用户登录行为
        // await this.model("action").log("user_login", "member", res.uid, res.uid, this.ip(), this.http.url);
        // console.log(111111111111121);
        // console.log(res);
        await this.session('webuser', res);
        return this.success({name: '登录成功！', user: res});
      } else { // 登录失败
        let fail;
        if (res instanceof Array && res.length > 1) {
          await this.session('users', res);
          res = -4;
        }
        switch (res) {
          case -1:
            fail = '用户不存在或被禁用';
            break; // 系统级别禁用
          case -2:
            fail = '密码错误';
            break;
          case -4:
            fail = '该账号对应多个用户';
            break;
          default:
            fail = '未知错误';
            break; // 0-接口参数错误（调试阶段使用）
        }
        return this.fail(res, fail);
      }
    } else {
      this.meta_title = '选择登陆用户';
      const users = await this.session('users');
      this.assign('users', users);
      return this.display();
    }
  }

  // 退出登录
  async logoutAction() {
    // 退出登录

    if (this.is_login) {
      await this.session('webuser', null);
      // 清楚cy_id
      // await this.session("wx_openid",null);
      // cysoIp9AH
      return this.redirect('/');
    } else {
      return this.redirect('/index');
    }
  }
  // 获取省市三级联动
  async getareaAction() {
    const pid = this.get('pid');
    const area = await this.model('area').where({parent_id: pid}).select();
    return this.json(area);
  }
};
